const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const connection = require('./database');
const util = require('util');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// 在线用户列表
let onlineUsers = new Set();

// API 路由放在前面
// 获取在线用户API
app.get('/api/online-users', (req, res) => {
    const query = `
        SELECT DISTINCT u.user_id, u.username 
        FROM users u 
        INNER JOIN login_logs l ON u.user_id = l.user_id 
        WHERE l.logout_time IS NULL 
        AND l.login_time >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
    `;
    
    connection.query(query, (error, results) => {
        if (error) {
            console.error('获取在线用户错误：', error);
            res.json({ success: false, message: '获取在线用户失败' });
            return;
        }
        res.json({ success: true, users: results });
    });
});

// 修改登录API
app.post('/api/login', (req, res) => {
    const { username, password } = req.body;
    
    connection.query(
        'SELECT * FROM users WHERE username = ?',
        [username],
        (error, results) => {
            if (error) {
                console.error('数据库错误：', error);
                res.json({ success: false, message: '数据库错误' });
                return;
            }
            
            if (results.length > 0) {
                const user = results[0];
                if (user.password === password) {
                    // 更新登录状态
                    connection.query(
                        'INSERT INTO login_logs (user_id, ip_address) VALUES (?, ?)',
                        [user.user_id, req.ip],
                        (error) => {
                            if (error) {
                                console.error('添加登录日志失败：', error);
                            }
                        }
                    );
                    
                    res.json({ 
                        success: true, 
                        user: {
                            user_id: user.user_id,
                            username: user.username,
                            email: user.email,
                            qq_number: user.qq_number,
                            phone_number: user.phone_number
                        }
                    });
                } else {
                    res.json({ success: false, message: '密码错误' });
                }
            } else {
                res.json({ success: false, message: '用户不存在' });
            }
        }
    );
});

// 修改注册API
app.post('/api/register', (req, res) => {
    const { username, password, email, qq_number, phone_number } = req.body;
    
    // 验证必填字段
    if (!username || !password || !email) {
        return res.json({ 
            success: false, 
            message: '用户名、密码和邮箱为必填项' 
        });
    }
    
    // 验证QQ号格式
    if (qq_number && !/^\d{5,11}$/.test(qq_number)) {
        return res.json({ 
            success: false, 
            message: 'QQ号格式不正确' 
        });
    }
    
    // 验证手机号格式
    if (phone_number && !/^1[3-9]\d{9}$/.test(phone_number)) {
        return res.json({ 
            success: false, 
            message: '手机号格式不正确' 
        });
    }
    
    // 首先检查用户名和邮箱是否已存在
    connection.query(
        'SELECT * FROM users WHERE username = ? OR email = ?',
        [username, email],
        (error, results) => {
            if (error) {
                console.error('查询用户失败：', error);
                return res.json({ 
                    success: false, 
                    message: '数据库错误' 
                });
            }
            
            if (results.length > 0) {
                return res.json({ 
                    success: false, 
                    message: '用户名或邮箱已存在' 
                });
            }
            
            // 插入新用户，确保 qq_number 和 phone_number 被正确插入
            const insertQuery = `
                INSERT INTO users 
                (username, password, email, qq_number, phone_number) 
                VALUES (?, ?, ?, ?, ?)
            `;
            
            connection.query(
                insertQuery,
                [username, password, email, qq_number || null, phone_number || null],
                (error, result) => {
                    if (error) {
                        console.error('注册用户失败：', error);
                        return res.json({ 
                            success: false, 
                            message: '注册失败' 
                        });
                    }
                    
                    // 返回注册成功的用户信息
                    res.json({ 
                        success: true, 
                        message: '注册成功',
                        user: {
                            user_id: result.insertId,
                            username,
                            email,
                            qq_number,
                            phone_number
                        }
                    });
                }
            );
        }
    );
});

// 获取聊天历史
app.get('/api/messages/:userId', (req, res) => {
    const currentUser = req.query.currentUser;
    const otherUser = req.params.userId;
    
    connection.query(
        `SELECT * FROM messages 
         WHERE (sender_id = ? AND receiver_id = ?) 
         OR (sender_id = ? AND receiver_id = ?)
         ORDER BY send_time ASC`,
        [currentUser, otherUser, otherUser, currentUser],
        (error, results) => {
            if (error) {
                res.json({ success: false, message: '获取消息失败' });
                return;
            }
            res.json({ success: true, messages: results });
        }
    );
});

// 发送消息
app.post('/api/messages', (req, res) => {
    const { sender_id, receiver_id, content } = req.body;
    const send_time = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    connection.query(
        'INSERT INTO messages (sender_id, receiver_id, content, send_time) VALUES (?, ?, ?, ?)',
        [sender_id, receiver_id, content, send_time],
        (error, results) => {
            if (error) {
                console.error('发送消息失败：', error);
                res.json({ success: false, message: '发送失败' });
                return;
            }
            res.json({ 
                success: true, 
                message: '发送成功', 
                messageId: results.insertId,
                send_time: send_time
            });
        }
    );
});

// 添加用户登出API
app.post('/api/logout', (req, res) => {
    const { user_id } = req.body;
    
    if (!user_id) {
        return res.status(400).json({ 
            success: false, 
            message: '用户ID不能为空' 
        });
    }
    
    connection.query(
        'UPDATE login_logs SET logout_time = NOW() WHERE user_id = ? AND logout_time IS NULL',
        [user_id],
        (error) => {
            if (error) {
                console.error('退出登录失败：', error);
                return res.status(500).json({ 
                    success: false, 
                    message: '退出失败' 
                });
            }
            res.json({ 
                success: true, 
                message: '退出成功' 
            });
        }
    );
});

// 获取新消息API
app.get('/api/new-messages/:userId', (req, res) => {
    const currentUser = req.query.currentUser;
    const otherUser = req.params.userId;
    const lastTime = req.query.lastTime || '1970-01-01';
    
    connection.query(
        `SELECT * FROM messages 
         WHERE ((sender_id = ? AND receiver_id = ?) 
         OR (sender_id = ? AND receiver_id = ?))
         AND send_time > ?
         ORDER BY send_time ASC`,
        [currentUser, otherUser, otherUser, currentUser, lastTime],
        (error, results) => {
            if (error) {
                console.error('获取新消息错误：', error);
                res.json({ success: false, message: '获取新消息失败' });
                return;
            }
            res.json({ success: true, messages: results });
        }
    );
});

// 获取户信息API
app.get('/api/user-info/:userId', (req, res) => {
    const userId = req.params.userId;
    
    connection.query(
        'SELECT user_id, username, email, qq_number, phone_number FROM users WHERE user_id = ?',
        [userId],
        (error, results) => {
            if (error) {
                console.error('获取用户信息错误：', error);
                res.json({ success: false, message: '获取用户信息失败' });
                return;
            }
            
            if (results.length > 0) {
                res.json({ success: true, user: results[0] });
            } else {
                res.json({ success: false, message: '用户不存在' });
            }
        }
    );
});

// 撤回消息API
app.post('/api/messages/:messageId/recall', (req, res) => {
    const messageId = req.params.messageId;
    const currentTime = new Date();
    
    console.log('尝试撤回消息:', messageId);
    
    // 首先检查消息是否存在
    connection.query(
        'SELECT * FROM messages WHERE message_id = ?',
        [messageId],
        (error, results) => {
            if (error) {
                console.error('查询消息失败：', error);
                return res.status(500).json({ 
                    success: false, 
                    message: '数据库错误' 
                });
            }
            
            if (!results || results.length === 0) {
                console.log('消息不存在:', messageId);
                return res.status(400).json({ 
                    success: false, 
                    message: '消息不存在' 
                });
            }
            
            const message = results[0];
            const sendTime = new Date(message.send_time);
            const timeDiff = Math.floor((currentTime - sendTime) / 1000 / 60); // 计算分钟差
            
            console.log('消息发送时间:', sendTime);
            console.log('当前时间:', currentTime);
            console.log('时间差(分钟):', timeDiff);
            
            if (timeDiff > 2) {
                return res.status(400).json({ 
                    success: false, 
                    message: '消息已超过2分钟，无法撤回' 
                });
            }
            
            // 更新消息状态为已撤回
            connection.query(
                'UPDATE messages SET status = "recalled", content = "此消息已撤回" WHERE message_id = ?',
                [messageId],
                (updateError) => {
                    if (updateError) {
                        console.error('更新消息状态失败：', updateError);
                        return res.status(500).json({ 
                            success: false, 
                            message: '撤回失败' 
                        });
                    }
                    
                    console.log('消息撤回成功:', messageId);
                    res.json({ 
                        success: true, 
                        message: '撤回成功' 
                    });
                }
            );
        }
    );
});

// 所有API路由
const apiRoutes = express.Router();

// 删除消息API
apiRoutes.post('/messages/:messageId/delete', (req, res) => {
    const messageId = req.params.messageId;
    const currentUser = req.body.currentUser;

    if (!currentUser || !currentUser.user_id) {
        return res.status(400).json({
            success: false,
            message: '用户信息无效'
        });
    }
    
    console.log('尝试删除消息:', messageId, '当前用户:', currentUser);
    
    // 首先检查消息是否存在并且是发送者
    connection.query(
        'SELECT * FROM messages WHERE message_id = ? AND sender_id = ?',
        [messageId, currentUser.user_id],
        (error, results) => {
            if (error) {
                console.error('查询消息失败：', error);
                return res.status(500).json({ 
                    success: false, 
                    message: '数据库错误' 
                });
            }
            
            if (!results || results.length === 0) {
                console.log('消息不存在或无权限删除:', messageId);
                return res.status(400).json({ 
                    success: false, 
                    message: '消息不存在或无权限删除' 
                });
            }
            
            // 从数据库中删除消息
            connection.query(
                'DELETE FROM messages WHERE message_id = ?',
                [messageId],
                (deleteError) => {
                    if (deleteError) {
                        console.error('删除消息失败：', deleteError);
                        return res.status(500).json({ 
                            success: false, 
                            message: '删除失败' 
                        });
                    }
                    
                    console.log('消息删除成功:', messageId);
                    res.json({ 
                        success: true, 
                        message: '删除成功' 
                    });
                }
            );
        }
    );
});

// 使用 /api 前缀
app.use('/api', apiRoutes);

// 静态文件服务放在最后
app.use(express.static('.'));

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`
    ================================
    即时通讯系统服务器
    作者：知识星球L站
    服务器运行在端口 ${PORT}
    ================================
    `);
}); 